home *** CD-ROM | disk | FTP | other *** search
- Path: drivel.ics.uci.edu!ucivax!gateway
- From: mheiberg@ahi.ICS.UCI.EDU (Michael Heiberg)
- Subject: Copy constructor optimization..
- Message-ID: <9602291637.aa17139@paris.ics.uci.edu>
- Date: 1 Mar 96 00:42:29 GMT
- Newsgroups: comp.lang.c++
-
- When constructing a variable from the return value of a function that
- returns a copy of that same type, the copy constructor will be called,
- but should the return statement copy the answer into the return space,
- and then copy that into the object being constructed, or should the
- return value be copy-constructed directly into the being-constructed
- object? For example:
-
- #include <iostream.h>
-
- class Vector {
- public:
- Vector() { cout << "Ctor "; }
- Vector(Vector& v) { cout << "Copy "; }
- };
-
- Vector foo(Vector &v) { return v; } // calls the copy-ctor
-
- main() {
- Vector a; // ctor
- Vector b=foo(a); // copy-ctor
- }
-
- Output:
- Ctor Copy
-
- Function foo returns a Vector by copy, calling the copy constructor, but
- Vector b needs to be constructed with that return value. I have tried
- this out on a Gnu, Borland, and Microsoft compiler, with optimizations
- turned off, and they all do this operation in one step, producing the
- output listed above. Is this just a very common and trivial optimization,
- or does the language actually specify that the constructed object is
- copy-constructed with v of foo?
-
- Any thoughts, answers, or references to relevant sections of one of
- Stroustrup's books would be appreciated. Reply by email please.
-
- Michael Heiberg - mheiberg@ics.uci.edu - http://www.ics.uci.edu/~mheiberg
-